import luckyexcel from 'luckyexcel'

const htClass = ['htCenter', 'htLeft', 'htRight']
const vtClass = ['htMiddle', 'htTop', 'htBottom']

function getOption (sheet) {
  const data = []
  const celldataCache = {}
  sheet.celldata.forEach(cell => {
    if (!data[cell.r]) {
      data[cell.r] = []
    }
    let v = cell.v
    if (v !== undefined && v.ct !== undefined && v.ct.s !== undefined && v.ct.s.length) {
      v = Object.assign(v, v.ct.s[0])
    }
    if (v.ht === undefined) {
      v.ht = 1
    }
    if (v.vt === undefined) {
      v.vt = 2
    }
    data[cell.r][cell.c] = v.v
    celldataCache[cell.r + '-' + cell.c] = v
  })
  const mergeCells = []
  sheet.config.merge && Object.keys(sheet.config.merge).forEach(m => {
    const mo = sheet.config.merge[m]
    mergeCells.push({
      row: mo.r,
      col: mo.c,
      rowspan: mo.rs,
      colspan: mo.cs
    })
  })
  const colWidths = []
  sheet.config.columnlen && Object.keys(sheet.config.customWidth).forEach(c => {
    colWidths[Number(c)] = sheet.config.columnlen[c] || sheet.defaultColWidth
  })
  const rowHeights = []
  sheet.config.rowlen && Object.keys(sheet.config.rowlen).forEach(r => {
    rowHeights[Number(r)] = sheet.config.rowlen[r]
  })
  for (let i = 0; i < rowHeights.length; i++) {
    if (!rowHeights[i]) {
      rowHeights[i] = 20
    }
  }
  const customRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
    const cell = celldataCache[row + '-' + col]
    if (cell) {
      if (cell.fs) {
        TD.style.fontSize = cell.fs + 'px'
      }
      if (cell.ff) {
        TD.style.fontFamily = cell.ff
      }
      if (cell.fc) {
        TD.style.color = cell.fc
      }
      if (cell.bg) {
        TD.style.backgroundColor = cell.bg
      }
      if (cell.bl) {
        TD.style.fontWeight = "600"
      }
      if (cell.it) {
        TD.style.fontStyle = 'italic'
      }
      if (cell.un === 0) {
        TD.style.textDecoration = 'underline'
      }
      TD.className = htClass[cell.ht] + ' ' + vtClass[cell.vt]
    }
    TD.innerHTML = value === undefined || value === null ? '' : value
  }
  const option = {
    rowHeights,
    colWidths,
    mergeCells,
    data,
    cells: function () {
      return {
        renderer: customRenderer
      }
    }
  }
  if (sheet.config.colhidden) {
    option.hiddenColumns = {
      indicators: true,
      columns: Object.keys(sheet.config.colhidden).map(k=>Number(k)),
    }
  }
  return option
}

function getHandsontableOptions (exportJson) {
  return exportJson.sheets.map(sheet => getOption(sheet))
}

export function xlsx2handson (excelFile) {
  return new Promise((resolve, reject) => {
    luckyexcel.transformExcelToLucky(excelFile, function (exportJson) {
      console.log(exportJson)
      const options = getHandsontableOptions(exportJson)
      resolve(options)
    });
  })
}
